from rest_framework.response import Response

from HttpTestcase.serializers import TestcaseReportsSerializer
from apps.HttpTestcase.models import TestcaseReports, TestsuiteTestcaseReports
from apps.HttpTestcase.models import TestsuiteReports
from rest_framework.views import APIView
from django.db.models import Sum
from apps.HttpTestcase.serializers import ReportsSerializer, TestsuiteReportsSerializer, \
    TestsuiteTestcaseReportsSerializer
import json
from utils.response import SuccessResponse


class TestcaseReportsDetails(APIView):
    """
    用例报告
    """

    def get(self, request, *args, **kwargs):
        # 版本号
        version = request.query_params.get('version')
        status = request.query_params.get('status', None)
        if version:
            testcase_results = TestcaseReports.objects.filter(version=version, is_delete=False)
            testcase_count = testcase_results.count()
            success = testcase_results.filter(status='PASS').count()
            fail = testcase_results.filter(status='FAIL').count()
            run_time = testcase_results.aggregate(Sum('elapsed_ms'))['elapsed_ms__sum']

            success_rate = round(((success / testcase_count) * 100), 2)

            if status:
                testcase_results = testcase_results.filter(status='status')

            data = []
            for i in testcase_results:
                testcase_result = ReportsSerializer(i).data
                data.append(testcase_result)
            response = {
                'testcase_count': testcase_count,
                'success': success,
                'fail': fail,
                'success_rate': success_rate,
                'run_time': run_time,
                'results': data
            }

            return SuccessResponse(data=response, msg="OK", )


class TestsuiteReportsAPIView(APIView):
    def get(self, request, *args, **kwargs):
        version = request.query_params.get('version')
        # status = request.query_params.get('status', None)
        if version:
            testcase_reports_list = TestcaseReports.objects.filter(version=version, is_delete=False)
            # 用例总数
            testcase_count = testcase_reports_list.count()
            # 用例成功数
            success = testcase_reports_list.filter(status='PASS').count()
            # 用例失败数
            fail = testcase_reports_list.filter(status='FAIL').count()
            # 执行时间
            run_time = testcase_reports_list.aggregate(Sum('elapsed_ms'))['elapsed_ms__sum']
            # 成功百分比
            success_rate = round(((success / testcase_count) * 100), 2)


            datas = []
            testsuite_reports_list = TestsuiteReports.objects.filter(version=version, is_delete=False)
            # 查询每条场景下：场景名称、所属项目、用例总数、通过数量、失败数量、通过比例 %、执行耗时(ms)、场景ID
            for testsuite_reports in testsuite_reports_list:
                testsuite_reports_dict = {'testsuite_name': testsuite_reports.testsuite_name,
                                          'project_name': testsuite_reports.project.name,
                                          'elapsed_ms': testsuite_reports.elapsed_ms,
                                          'testsuite_id': testsuite_reports.testsuite_id,
                                          'status': testsuite_reports.status,
                                          }
                testsuite_reports_id = testsuite_reports.id
                # 查询用例报告属于testsuite报告的数据并统计
                testsuite_count, testsuite_success, testsuite_fail = 0, 0, 0
                testsuite_count += testcase_reports_list.filter(testsuite_reports_id=testsuite_reports_id).count()
                testsuite_success += testcase_reports_list.filter(testsuite_reports_id=testsuite_reports_id, status='PASS').count()
                testsuite_fail += testcase_reports_list.filter(testsuite_reports_id=testsuite_reports_id, status='FAIL').count()
                testsute_rate = round(((testsuite_success / testsuite_count) * 100), 2)
                testsuite_reports_dict['count'] = testsuite_count
                testsuite_reports_dict['success'] = testsuite_success
                testsuite_reports_dict['fail'] = testsuite_fail
                testsuite_reports_dict['rate'] = testsute_rate


                # 一对多查询，查询出该场景下所有用例
                testcase_data_list = []
                testcase_reports_models = testsuite_reports.testsuite_reports.all()
                for testcase_reports in testcase_reports_models:
                    data = {
                        'testcase_name': testcase_reports.testcase_name,
                        'api_name': testcase_reports.api_name,
                        'url': testcase_reports.url,
                        'actual_status_code': testcase_reports.actual_status_code,
                        'elapsed_ms': testcase_reports.elapsed_ms,
                        'actual_response_data': json.dumps(testcase_reports.actual_response_data),
                        'failure_reason': testcase_reports.failure_reason,
                        'testcase_id': testcase_reports.testcase_id,
                        'status': testcase_reports.status,
                    }
                    testcase_data_list.append(data)
                    # testcase_reports_list.append(TestcaseReportsSerializer(testcase_reports).data)

                testsuite_reports_dict['testcase_data'] = testcase_data_list
                datas.append(testsuite_reports_dict)


            response = {
                'count': testcase_count,
                'success': success,
                'fail': fail,
                'success_rate': success_rate,
                'run_time': run_time,
                'data': datas
            }

            return SuccessResponse(data=response, msg="OK", )
